import jwt
from datetime import datetime, timedelta
import re

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7
from cryptography.hazmat.backends import default_backend
from base64 import b64decode

from passlib.hash import bcrypt

SECRET_KEY = 'mtzlgz'
ALGORITHM = 'HS256'

def create_access_token(data: dict, expires_delta: timedelta = None):
  to_encode = data.copy()
  if expires_delta:
    expire = datetime.utcnow() + expires_delta
  else:
    expire = datetime.utcnow() + timedelta(minutes=15)
  to_encode.update({"exp": expire})
  encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  return encoded_jwt

def hash_psd(psd):
    return bcrypt.hash(psd)

def camelToSnake(str):
    return re.sub(r'(?<!^)(?=[A-Z])', '_', str).lower()


def timestampToDatetime(timestamp):
    return datetime.fromtimestamp(timestamp)

def setResponseData(code, msg, data):
    return {
        "code": code,
        "msg": msg,
        "data": data
    }


def decrypt_AES_ECB(encrypted_str, key):
    backend = default_backend()
    key_bytes = key.encode('utf-8')
    encrypted_bytes = b64decode(encrypted_str)

    cipher = Cipher(algorithms.AES(key_bytes), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    decrypted_padded = decryptor.update(encrypted_bytes) + decryptor.finalize()

    # 创建PKCS7 unpadder
    unpadder = PKCS7(128).unpadder()
    decrypted_data = unpadder.update(decrypted_padded) + unpadder.finalize()

    return decrypted_data.decode('utf-8')

def setResponse(data):
   if(data) :
      return setResponseData('10000000', 'success', data)
   else:
      return setResponseData('00000000', 'fail', '')
   

  
def datetime_to_timestamp(obj):
    if isinstance(obj, datetime):
        return int(obj.timestamp())
    raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable")

